package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.Storage;
import com.example.demo.mapper.StorageMapper;
import com.example.demo.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * <p>
 * 库存表 服务实现类
 * </p>
 *
 * @author ElonChung
 * @since 2020-05-13
 */
@Slf4j
@Service
public class StorageServiceImpl extends ServiceImpl<StorageMapper, Storage> implements StorageService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reduceStorage(Integer goodsId, Integer count) {
        Storage storage = getByGoodsId(goodsId);

        try {
//            int b = 1 / 0;
            if (storage != null) {
                log.info("减库存冻结数=={}=={}=>", storage.getCount(), count);
                storage.setCount(storage.getCount() - count);
                storage.setFreeze(storage.getFreeze() + count);
                updateById(storage);
            }

        } catch (Exception e) {
            e.printStackTrace();
            // 不主动回滚 有错误还是会提交事务的
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void freeze(Integer goodsId, Integer count) {

        Storage storage = getByGoodsId(goodsId);
        if (storage != null) {
            storage.setFreeze(storage.getFreeze() + count);
            updateById(storage);
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unfreeze(Integer goodsId, Integer count) {

        Storage storage = getByGoodsId(goodsId);
        if (storage != null) {
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.set("freeze", storage.getFreeze() - count);
            update(storage, updateWrapper);
        }
    }

    public Storage getByGoodsId(Integer goodsId) {
        QueryWrapper<Storage> storageQueryWrapper = new QueryWrapper<>();
        storageQueryWrapper.eq("goods_id", goodsId);
        return getOne(storageQueryWrapper);
    }
}
